<?php
namespace App\Controller;
use Common\Controller\HomebaseController;

class BaseController extends HomebaseController  {
    protected $userinfo;
    function _initialize()
    {
        parent::_initialize();
        if(CONTROLLER_NAME != 'Login' && CONTROLLER_NAME != 'Public'){
            $uid = I('uid',0,'intval');
            $token = I('token');
            $this->userinfo = M('member')->where("uid = %d",array($uid))->find();
            if(!$this->userinfo || $this->userinfo['token'] != $token ){
                $this->error(10010,'登录超时，请重新登录');
            }
        }
        header("Access-Control-Allow-Origin: *");
    }

    /**
     * 成功
     * @param array $data
     * @param string $message
     */
    protected function success( $message = 'success',$data = array(), $extends = null)
    {
        $result = array('code' => 200, 'data' => $data, 'message' => $message);
        if(!$data){
            unset($result['data']);
        }
        if($extends){
            $result = array_merge($result,$extends);
        }
        echo json_encode($result);
        exit;
    }

    /**
     * 失败
     * @param string $code
     * @param string $message
     * @param array $data
     */
    protected function error($code, $message = 'error', $data = array())
    {
        $result = array('code' => $code, 'data' => $data, 'message' => $message);
        if(!$data){
            unset($result['data']);
        }
        echo json_encode($result);
        exit;
    }
}